import {
    RequestConfig,
    RunTimeLayoutConfig,
    history,
    matchRoutes,
} from '@umijs/max';
// import { Settings } from '@ant-design/pro-components/defaultSettings'
import Logo from '@/assets/logo.png';
import { Link, getLocale } from '@umijs/max';
import ActionsRender from './pages/Layout/actionsRender';
import AvatarRender from './pages/Layout/avatarRender';
import MenuFooterRender from './pages/Layout/menuFooterRender';
import Error403 from './pages/error/Error403';
import { toImages } from './utils';

// 运行时配置
// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<IGlobal.IInitialState> {
    return {
        site:null,
        user: null,
        isAuthName: null,
        auth: null,
    };
}
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
    return {
        logo: Logo,
        unAccessible: <Error403 />,
        headerTitleRender: (logo, title) => {
            return (
                <div
                    id="customize_menu_header"
                    onClick={(e) => e.stopPropagation()}
                >
                    {logo}
                    {title}
                </div>
            );
        },
        menu: {},
        layout: 'mix',
        splitMenus: true,
        fixedHeader: true,
        fixSiderbar: true,
        avatarProps: {
            title: initialState?.user?.username,
            src: toImages(initialState?.user?.avatar),
            size: 'small',
            render: (props, dom) => <AvatarRender dom={dom} />,
        },
        menuItemRender: (menuItemProps, defaultDom) => {
            if (
                menuItemProps.isUrl ||
                !menuItemProps.path ||
                location.pathname === menuItemProps.path
            ) {
                return defaultDom;
            }
            return (
                <>
                    {defaultDom}
                    <Link
                        to={menuItemProps.path}
                        state={menuItemProps.state}
                    ></Link>
                </>
            );
        },
        actionsRender: () => {
            return ActionsRender;
        },
        // footerRender: () => <FooterRender></FooterRender>,
        menuFooterRender: () => <MenuFooterRender></MenuFooterRender>,
    };
};
/* 路由发生变化 */
export function onRouteChange({ clientRoutes, location }) {
    const route = matchRoutes(clientRoutes, location.pathname)?.pop()?.route;
    if (route && route.children && route?.children.length > 0) {
        history.push(route.path + '/' + route?.children[0].path);
    }
}

export const request: RequestConfig = {
    timeout: 180000,
    baseURL: '/dev-api', // 请求的根域名
    headers: {
        'content-type': 'application/json;charset=UTF-8',
    },
    // other axios options you want
    errorConfig: {
        errorHandler(err: Record<string, any>) {
            if (err?.response?.status === 504) {
                history.replace('/504');
            }
            console.error(err);
        },
        errorThrower(err) {
            console.log(err);
        },
    },

    //为 request 方法添加请求阶段的拦截器。
    requestInterceptors: [
        (url, options) => {
            const token = localStorage.getItem('token');
            if (token) {
                options.headers['xzdToken'] = token;
            }
            if (options.method === 'post') {
                options.data.lang = getLocale() === 'zh-CN' ? 'zh' : 'ru';
            } else {
                options.params.lang = getLocale() === 'zh-CN' ? 'zh' : 'ru';
            }
            options.url = encodeURI(options.url as string);
            return { url, options };
        },
    ],
    responseInterceptors: [
        (response: any) => {
            const { data } = response;
            if (data.code === 201) {
                history.replace('/login');
                return Promise.reject(data);
            } else if (data.code === 500) {
                // do something
                // history.replace('/504');
                return Promise.reject(data);
            } else if (data.code !== 200 && data.code !== 1) {
                // do something
                return Promise.reject(data);
            }
            return response;
        },
    ],
};
